import os
import sys
import pathlib

project_path = pathlib.Path(os.path.abspath(__file__)).parent.parent.parent
sys.path.append(str(project_path))

from etc.question_answer_config import es_hosts, template_path, is_question_classifier
from elasticsearch import Elasticsearch

from shell.knowledge_graph.question_classifier import Classifier
from shell.knowledge_graph.question_parser import QAParser
from shell.knowledge_graph.answer_filter import AnswerFilter
from shell.knowledge_graph.cypher_search import CypherSearch
from utility.import_log import flog

log = flog(__file__)


class QA(object):
    def __init__(self):
        self.value_list = []
        self.attr_list = []
        self.node1_name = None
        self.node2_name = None
        self.es =Elasticsearch()
        self.parsers = QAParser()
    def answer(self, question):
        value_list, attr_list = self.parsers.es_parser(self.es, question, topn=5, threshold=3)

        if not len(value_list) or not len(attr_list):
            log.info(f'查询无结果！')
            return ''

        filters = AnswerFilter(value_list, attr_list)

        cyphers = CypherSearch(template_path)

        if is_question_classifier:
            classifiers = Classifier()
            filters.filter_by_nodes(question, classifiers)
            self.node1_name = filters.node1_name
            self.node2_name = filters.node2_name
        else:
            filters.filter_by_shortestpath(cyphers)

        if not len(filters.value_list) or not len(filters.attr_list):
            log.info(f'查询无结果！')
            return ''

        cypher = cyphers.template_match(filters.value_list[0], filters.attr_list[0])

        self.value_list = filters.value_list
        self.attr_list = filters.attr_list
        return cypher


if __name__ == "__main__":
    question = '9444089568361182的贷款开户日期？'
    qa = QA()
    qa.answer(question)
